-module(cus_sup).

-behaviour(supervisor).
-behaviour(ejabberd_config).

-export([start_link/0]).

-export([init/1, opt_type/1]).



-include("ejabberd.hrl").
-include("logger.hrl").
-include("cus_pb.hrl").
-include("cus.hrl").



start_link() ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).



init([]) ->
    ets:new(cus_config_tab, [named_table, public, set]),
    ets:new(cid_and_sid_tab, [named_table, public, set]),
    cus_config:start(),
    start_lib(),
    start_mysql(),
    start_redis(),
    start_token_redis(),
    start_push(),
    cus_proc_manage:start(),
    nodes_ping(),
    cus_migrate:migrate(),
    List = server_tuples(),
    {ok, {{one_for_one, 5, 10}, List}}.


server_tuples() ->
    [server_tuple(cus_dump), server_tuple(cus_http)].


server_tuple(Service) ->
    {Service,
     {Service, start_link, []},
     permanent,
     5000,
     worker,
     [Service]}.
 

start_lib() ->
    ssl:start(),
    inets:start(),
    timer:start().


start_mysql() ->
    [Host, Port, User, Pwd, DB, Encode, Size] = cus_config:mysql(),
    cus_mysql:start(?list(Host), Port, ?list(User), ?list(Pwd), ?list(DB), Encode, Size).


start_redis() ->
    [Host, Port, DB, Pwd, Size] = cus_config:redis(),
    cus_redis:start(?list(Host), Port, DB, ?list(Pwd), Size).
    

start_token_redis() ->
    [Host, Port, DB, Pwd, Size] = cus_config:token_redis(),
    cus_token_redis:start(?list(Host), Port, DB, ?list(Pwd), Size).


start_push() ->
    case cus_config:ios() of
        [Host, Cert, Key, Size] ->
            cus_push:start(?list(Host), ?list(Cert), ?list(Key), Size);
        [Host, Cert, Key, Pwd, Size] ->
            cus_push:start(?list(Host), ?list(Cert), ?list(Key), ?list(Pwd), Size)
    end.


nodes_ping() ->
    AllNodes = cus_config:access_nodes() ++ cus_config:business_nodes(),
    node_ping(AllNodes).


node_ping([]) ->
    skip;
node_ping([Node | L]) ->
    case net_adm:ping(Node) of
        pong ->
            success;
        _ ->
            ?ERROR_MSG("~p ping ~p failed, please check the network", [node(), Node])
    end,
    node_ping(L).


opt_type(cus) ->
    fun(V) -> V end;
opt_type(_) ->
    [cus].